package org.example.mulitithreading.ex2p;

public class SellTicket3 extends Thread {
    private static int ticket = 100;
    static final Object lock = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (lock) { // 使用synchronized在某一线程使用时对其上锁，进行原子操作
                if (ticket <= 0) {
                    //卖完了
                    break;
                } else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticket + "张票");
                }
            }
        }
    }
}
